const express = require("express");
const path = require("path");
const _ = require("lodash");
const httpProxy = require("http-proxy");
const httpProxyMiddleware = require("http-proxy-middleware");

const app = express();
const logError = (err, req, res) => {
    console.error(err);
    if (req.headers.upgrade && req.headers.upgrade == "websocket") {
        return;
    }
    res.writeHead(500, {
        "Content-Type": "application/json; charset=utf-8"
    });
    res.end(`{ "data": "${err.name + " : " + err.message}", "code": "0" }`);
};
const mProxy = httpProxyMiddleware("/", {
    target: "http://127.0.0.1",
    pathRewrite: function(_path, req) {
        if (_.startsWith(_path, "/2.0")) {
            return _path.replace("/2.0", "");
        }
        if (_.startsWith(_path, "/1.0")) {
            return _path.replace("/1.0", "");
        }
        if (_.startsWith(_path, "/cloud/1.0")) {
            return _path.replace("/cloud/1.0", "/cloud");
        }
        if (_.startsWith(_path, "/uploads")) {
            return path.basename(_path);
        }
    },
    router: function(req) {
        if (_.startsWith(req.path, "/2.0")) {
            return "http://127.0.0.1:3082";
        }
        if (_.startsWith(req.path, "/1.0")) {
            return "http://127.0.0.1:3061";
        }
        if (_.startsWith(req.path, "/cloud/1.0")) {
            return "http://127.0.0.1:3061";
        }
        if (_.startsWith(req.path, "/uploads")) {
            return "http://img.qingful.com";
        }
    },
    changeOrigin: true,
    ws: true,
    onError: logError
});
const hProxy = httpProxy.createProxyServer({});
hProxy.on("error", logError);

app.use((req, res, next) => {
    const path = req.path;
    if (/^\/MP_verify_(\w*).txt$/.test(path)) {
        let paths = path.split("/MP_verify_");
        paths = paths[1].split(".txt");

        res.send(paths[0]);
    } else {
        next();
    }
});
app.use((req, res, next) => {
    const proxyTarget = req.get("Proxy") || req.query.Proxy;
    const proxyChangeOrigin =
        req.get("ProxyChangeOrigin") === "false" ? false : true;
    const proxyIgnorePath =
        req.get("ProxyIgnorePath") === "false" ? false : true;
    if (proxyTarget) {
        return hProxy.web(req, res, {
            target: proxyTarget.replace("www.qingful.com", "www2.qingful.com"),
            changeOrigin: proxyChangeOrigin,
            ignorePath: proxyIgnorePath
        });
    }

    next();
});
app.use(express.static(__dirname + "/www"));
app.use(mProxy);
app.use((req, res, next) => {
    res.end(`api ${new Date()}`);
});

const server = app.listen(3080);
server.on("upgrade", mProxy.upgrade);
